import { profileInfo } from '@/api/user'
import { UserInfo } from '@/types/userTypes'
import { clearToken, hasToken } from '@/utils/storage'
import { defineStore } from 'pinia'
import { showToast } from 'vant'
import { ref } from 'vue'

const userStore = defineStore('user', () => {
  const userInfo = ref<UserInfo | null>(null)

  const setUserInfo = (info: any) => {
    userInfo.value = { ...userInfo.value, ...info }
  }

  // 清除用户信息
  const clearUserInfo = () => {
    userInfo.value = null
    localStorage.removeItem('user_store')
    clearToken()
  }

  // 是否登录
  const isLogin = () => {
    return !!userInfo.value && hasToken()
  }

  const getUserInfo = async () => {
    const { data } = await profileInfo()
    if (data.code === 0) {
      setUserInfo(data.data)
      return true
    } else {
      showToast(data.msg)
      clearUserInfo()
      return false
    }
  }

  return {
    userInfo,
    setUserInfo,
    clearUserInfo,
    isLogin,
    getUserInfo
  }
}, {
  persist: {
    storage: localStorage,
    paths: ['userInfo'],
    key: 'user_store'
  } as any
})

export default userStore